/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bankmanagement;
import java.text.ParseException;
import java.util.*;
import java.io.*;
import java.text.SimpleDateFormat;
/**
 *
 * @author NDA
 */
public class BankManagement {
    static Scanner input = new Scanner(System.in);
    static String dir = "data/";
    
       
    public static String convertDateToString(Date date){
        String format = "dd-MM-yyyy";
        SimpleDateFormat mySimpleDateFormat = new SimpleDateFormat(format);
        return mySimpleDateFormat.format(date);
    }
    
    public static Date convertStringToDate(String str) throws ParseException{
        String format = "dd-MM-yyyy";
        SimpleDateFormat mySimpleDateFormat = new SimpleDateFormat(format);
    try {
        return mySimpleDateFormat.parse(str);
    } catch (ParseException e) {
        return null;
    }
    }
    
    public static String[] listFile(){
        File directory = new File(dir);
        String[] listFile = null;
        int i=0;
        if (!directory.isDirectory()) {
        System.out.println("No directory provided");
        }

        FilenameFilter filefilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
            return name.endsWith(".txt");
            }
        };

        String[] filenames = directory.list(filefilter);

        return filenames;
        }
    
    static void writeData(Account account, PrintWriter out) throws IOException {
        account.writeData(out);
    }
    
    static Account readData(BufferedReader in) throws IOException, ParseException {
        Account account = new Account();
        account.readData(in);
        return account;
    }

    public static boolean viewAccount(int accountNumber) throws ParseException{
        boolean check=false;
        String fileName = dir + Integer.toString(accountNumber) + ".txt";
        File f = new File(fileName);
        if (f.exists()){
            check = true;
            try {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            Account a = readData(in);
            a.printData();
            in.close();
        
            } catch (IOException e) {
            System.out.println("Error " + e);
            System.exit(1);
        }
        }
        
        return check;
    }
    
    public static void checkAccount(int accountNumber, String password) throws ParseException{
        String fileName = Integer.toString(accountNumber);
        fileName = dir + fileName + ".txt";
        File f = new File(fileName);
        if (!f.exists()) System.out.println("Account number " + accountNumber + " is not exist!"); 
        else {
            try {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            Account a = readData(in);
            String pass = a.password;
            in.close();
            if (password.equals(pass)){
                if(a.accountType)
                functionAdmin(a.accountNumber);
                else functionCustomer(a.accountNumber);
                }
            else System.out.println("Password is incorrect!");
            } catch (IOException e) {
            System.out.print("Error: " + e);
            System.exit(1);
        }
        }
        
    }
    
    public static void functionAdmin(int accountNumber) throws ParseException, FileNotFoundException, IOException{
        boolean check = true;
        String fileName = dir + Integer.toString(accountNumber) + ".txt";
        File f = new File(fileName);
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            Account a = readData(in);
            in.close();
        int choise;
        
            System.out.printf("      |Welcome %20s|\n",a.accountName);
            System.out.println("---------------------------------------");
            System.out.println("Please select");
            System.out.println("1.Creat new account");
            System.out.println("2.Search account");
            System.out.println("3.Edit account");
            System.out.println("4.Delete account");
            System.out.println("5.Account query");
            System.out.println("6.Withdraw money");
            System.out.println("7.Transfer money");
            System.out.println("8.Exit");
            System.out.print("Enter your choice: ");
            choise=input.nextInt();
            input.nextLine();//giai phong ky tu enter neu co
            System.out.println("=======================================");
            switch(choise){
                case 1://creat new account
                    creatAccount(accountNumber);
                    break;
                case 2://Search account
                    searchAccount(accountNumber);
                    break;
                case 3://Edit account
                    editAccount(accountNumber);
                    break;
                case 4://Delete account
                    deleteAccount(accountNumber);
                    break;
                case 5://Delete account
                    accountQuery(accountNumber, check);
                    break;
                case 6://Delete account
                    withdrawMoney(accountNumber, check);
                    break;
                case 7://Delete account
                    transferMoney(accountNumber, check);
                    break;
                case 8://Exit
                    System.out.println("Goodbye! See you again!");
                    break;
                default: System.out.println("Please enter your choice again!");
            }
       
    }
    
    public static void creatAccount(int accAdmin) throws ParseException, FileNotFoundException, IOException{
        String fileName = new String();
        String temp = new String();
        int accountNumber;
        String password;
        String accountName;
        boolean accountType;
        boolean gender;
        Date dateOfBirth;
        String email;
        double balance;
        System.out.println("              |Creat new account|");
        System.out.println("---------------------------------------");
        System.out.print("Account Number              : ");
        temp = input.nextLine();
        accountNumber = Integer.parseInt(temp);
        System.out.print("Password                    : ");
        password = input.nextLine();
        System.out.print("Account Name                : ");
        accountName = input.nextLine();
        System.out.print("Account Type(admin/customer): ");
        temp = input.nextLine();
        if(temp.equalsIgnoreCase("admin")) accountType = true; else accountType = false;
        System.out.print("Gender         (male/female): ");
        temp = input.nextLine();
        if(temp.equalsIgnoreCase("male")) gender = true; else gender = false;
        System.out.print("Birthday        (dd-mm-yyyy): ");
        temp = input.nextLine();
        dateOfBirth = convertStringToDate(temp);
        System.out.print("Email                       : ");
        email = input.nextLine();
        System.out.print("Balance                     : ");
        balance = input.nextDouble();
        fileName = dir + String.valueOf(accountNumber) + ".txt";
        Account a = new Account(accountNumber, password, accountName, accountType, gender, 
                dateOfBirth, email, balance);
        try {
        PrintWriter out = new PrintWriter(new FileWriter(fileName));
        writeData(a, out);
        out.close();
        } catch (IOException e) {
        System.out.print("Error: " + e);
        System.exit(1);
        }
        System.out.println("Please enter to return admin page!");
        input.nextLine();//giai phong ky tu enter
        functionAdmin(accAdmin);
        System.out.println("=======================================");
    }
    
    public static void searchAccount(int accAdmin) throws ParseException, FileNotFoundException, IOException{
        int choise;
            System.out.println("                |SEARCH|");
            System.out.println("---------------------------------------");
            System.out.println("You want to search by");
            System.out.println("1.Account Number");
            System.out.println("2.Account Name");
            System.out.println("3.Email");
            System.out.println("4.Back to Admin page");
            System.out.println("5.Exit");
            System.out.print("Enter your choice: ");
            choise=input.nextInt();
            input.nextLine();//giai phong ky tu enter neu co
            System.out.println("=======================================");
            switch(choise){
                case 1://creat new account
                    searchByAccountNumber(accAdmin);
                    break;
                case 2://Search account
                    searchByAccountName(accAdmin);
                    break;
                case 3://Delete account
                    searchByEmail(accAdmin);
                    break;
                case 4://back
                    functionAdmin(accAdmin);
                    break;
                case 5://back
                    System.out.println("Goodbye! See you again!");
                    break;
                default: System.out.println("Please enter your choice again!");
            }
    }
    
    public static void searchByAccountNumber(int accAdmin) throws ParseException, FileNotFoundException, IOException{
        int accountNumber;
        String temp = new String();
        System.out.println("      |SEARCH BY ACCOUNT NUMBER|");
        System.out.println("---------------------------------------");
        System.out.print("Enter the Account Number: ");
        temp = input.nextLine();
        accountNumber = Integer.parseInt(temp);
        System.out.println("---------------------------------------");
        System.out.println("Search result:");
        System.out.println("|Account number |  Password  | Account name     "
                + "| Account type | Gender |Date Of Birth |           Email         |  Balance  |");
        System.out.println("-------------------------------------------"
                + "-------------------------------------------------------------------------------------");
        boolean check = viewAccount(accountNumber);
        if(!check) System.out.println("Account number "+accountNumber+" is not exist!");
        
        
        System.out.println("Please enter to return search page!");
        input.nextLine();//giai phong ky tu enter
        System.out.println("=======================================");
        searchAccount(accAdmin);
    }
    
    public static void searchByAccountName(int accAdmin) throws ParseException, FileNotFoundException, IOException{
        String accountName = new String();
        int count=0;
        String[] listFile = null;
        System.out.println("        |SEARCH BY ACCOUNT NAME|");
        System.out.println("---------------------------------------");
        System.out.print("Enter the Account Name: ");
        accountName = input.nextLine();
        System.out.println("---------------------------------------");
        listFile = listFile();
        
        System.out.println("Search result:");
        System.out.println("|Account number |  Password  | Account name     "
                + "| Account type | Gender |Date Of Birth |           Email         |  Balance  |");
        System.out.println("-------------------------------------------"
                + "------------------------------------------------------------------------------------");
        //int count = viewAccount(accountNumber);
        
        for(String t:listFile){
            
            StringBuilder std = new StringBuilder(t);
            std = std.delete(std.length()-4,std.length());
            t = std.toString();
            try {
            BufferedReader in = new BufferedReader(new FileReader(dir + t +".txt"));
            Account a = readData(in);
            if (a.accountName.equalsIgnoreCase(accountName)){
                a.printData();
                count++;
            }
            in.close();
            } catch (IOException e) {
            System.out.println("Error " + e);
            System.exit(1);
            }
            
        }
        if (count==0) System.out.println("Can not found account name "+accountName);
        System.out.println("Please enter to return search page!");
        input.nextLine();//giai phong ky tu enter
        System.out.println("=======================================");
        searchAccount(accAdmin);
    }
    
        
    public static void searchByEmail(int accAdmin) throws ParseException, FileNotFoundException, IOException{
        
        String email = new String();
        int count=0;
        String[] listFile = null;
        System.out.println("           |SEARCH BY EMAIL|");
        System.out.println("---------------------------------------");
        System.out.print("Enter the Email: ");
        email = input.nextLine();
        System.out.println("---------------------------------------");
        listFile = listFile();
        
        System.out.println("Search result:");
        System.out.println("|Account number |  Password  | Account name     "
                + "| Account type | Gender |Date Of Birth |           Email         |  Balance  |");
        System.out.println("-------------------------------------------"
                + "------------------------------------------------------------------------------------");
        //int count = viewAccount(accountNumber);
        
        for(String t:listFile){
            
            StringBuilder std = new StringBuilder(t);
            std = std.delete(std.length()-4,std.length());
            t = std.toString();
            try {
            BufferedReader in = new BufferedReader(new FileReader(dir + t +".txt"));
            Account a = readData(in);
            if (a.email.equalsIgnoreCase(email)){
                a.printData();
                count++;
            }
            in.close();
            } catch (IOException e) {
            System.out.println("Error " + e);
            System.exit(1);
            }
            
        }
        if (count==0) System.out.println("Can not found account name "+email);
        System.out.println("Please enter to return search page!");
        input.nextLine();//giai phong ky tu enter
        System.out.println("=======================================");
        searchAccount(accAdmin);
    }
    
    public static void editAccount(int accAdmin) throws ParseException, FileNotFoundException, IOException{
        String fileName = new String();
        int accountNumber;
        String password;
        String accountName;
        boolean accountType;
        boolean gender;
        Date dateOfBirth;
        String email;
        double balance;
        String temp = new String();
        System.out.println("           |EDIT ACCOUNT|");
        System.out.println("---------------------------------------");
        System.out.print("Enter the Account Number: ");
        temp = input.nextLine();
        accountNumber = Integer.parseInt(temp);
        System.out.println("---------------------------------------");
        System.out.println("|Account number |  Password  | Account name     "
                + "| Account type | Gender |Date Of Birth |           Email         |  Balance  |");
        System.out.println("-------------------------------------------"
                + "------------------------------------------------------------------------------------");
        boolean check = viewAccount(accountNumber);
        if(!check) System.out.println("Account number "+accountNumber+" is not exist!");
        else{
        
            System.out.println("              |Enter new information|");
            System.out.println("---------------------------------------");
            System.out.println("Account Number              : "+ accountNumber);
            System.out.print("Password                    : ");
            password = input.nextLine();
            System.out.print("Account Name                : ");
            accountName = input.nextLine();
            System.out.print("Account Type(admin/customer): ");
            temp = input.nextLine();
            if(temp.equalsIgnoreCase("admin")) accountType = true; else accountType = false;
            System.out.print("Gender         (male/female): ");
            temp = input.nextLine();
            if(temp.equalsIgnoreCase("male")) gender = true; else gender = false;
            System.out.print("Birthday        (dd-mm-yyyy): ");
            temp = input.nextLine();
            dateOfBirth = convertStringToDate(temp);
            System.out.print("Email                       : ");
            email = input.nextLine();
            System.out.print("Balance                     : ");
            balance = input.nextDouble();
            fileName = dir + String.valueOf(accountNumber) + ".txt";
            Account a = new Account(accountNumber, password, accountName, accountType, gender, 
                dateOfBirth, email, balance);
            try {
            PrintWriter out = new PrintWriter(new FileWriter(fileName));
            writeData(a, out);
            out.close();
            } catch (IOException e) {
            System.out.print("Error: " + e);
            }
        }
        System.out.println("Please enter to Administrator page!");
        input.nextLine();//giai phong ky tu enter
        System.out.println("=======================================");
        functionAdmin(accAdmin);
    }
    
    public static void deleteAccount(int accAdmin) throws ParseException, FileNotFoundException, IOException{
        String temp = new String();
        int accountNumber;
        System.out.println("           |DELETE ACCOUNT|");
        System.out.println("---------------------------------------");
        System.out.print("Enter the Account Number: ");
        temp = input.nextLine();
        accountNumber = Integer.parseInt(temp);
        System.out.println("---------------------------------------");
        File file = new File(dir + temp + ".txt");
        System.out.println("---------------------------------------");
        System.out.println("|Account number |  Password  | Account name     "
                + "| Account type | Gender |Date Of Birth |           Email         |  Balance  |");
        System.out.println("-------------------------------------------"
                + "------------------------------------------------------------------------------------");
        boolean check = viewAccount(accountNumber);
        if(!check) System.out.println("Account number "+accountNumber+" is not exist!");
        else  {
            System.out.print("Are you sure want to delete?(y/n) ");
            temp = input.nextLine();
            if (temp.equalsIgnoreCase("y")){
                file.delete();
                System.out.println("Account "+accountNumber +" is deleted!");
            }
        }
        
        System.out.println("Please enter to return Administrator page!");
        input.nextLine();//giai phong ky tu enter
        System.out.println("=======================================");
        functionAdmin(accAdmin);
    }
    
    public static void functionCustomer(int accountNumber) throws ParseException, FileNotFoundException, IOException{
        boolean check = false;
        String fileName = dir + Integer.toString(accountNumber) + ".txt";
        File f = new File(fileName);
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            Account a = readData(in);
            in.close();
        
        int choise;
            System.out.printf("     |Welcome%20S|\n",a.accountName);
            System.out.println("---------------------------------------");
            System.out.println("Please select");
            System.out.println("1.Account query");
            System.out.println("2.Withdraw money");
            System.out.println("3.Transfer money");
            System.out.println("4.Exit");
            System.out.print("Enter your choice: ");
            choise=input.nextInt();
            input.nextLine();//giai phong ky tu enter neu co
            System.out.println("=======================================");
            switch(choise){
                case 1://creat new account
                    accountQuery(accountNumber, check);
                    break;
                case 2://Search account
                    withdrawMoney(accountNumber, check);
                    break;
                case 3://Edit account
                    transferMoney(accountNumber, check);
                    break;
                case 4://Exit
                    System.out.println("Goodbye! See you again!");
                    break;
                default: System.out.println("Please enter your choice again!");
            }
    }
    
    public static void accountQuery(int accountNumber, boolean check) throws ParseException, FileNotFoundException, IOException{
        String fileName = dir + Integer.toString(accountNumber) + ".txt";
        File f = new File(fileName);
        System.out.println("             |ACCOUNT QUERY|");
        System.out.println("---------------------------------------");
        try {
        BufferedReader in = new BufferedReader(new FileReader(fileName));
        Account a = readData(in);
        System.out.printf("You have: %20s\n", a.balance +" $");
        in.close();
        } catch (IOException e) {
        System.out.println("Error " + e);
        System.exit(1);
        }
        System.out.println("Please enter to continue!");
        input.nextLine();//giai phong ky tu enter
        System.out.println("=======================================");
        if(!check)
            functionCustomer(accountNumber);
        else
            functionAdmin(accountNumber);
    }
    
    public static void withdrawMoney(int accountNumber, boolean check) throws ParseException, FileNotFoundException, IOException{
        double balance;
        System.out.println("               |WITHDRAW|");
        System.out.println("---------------------------------------");
        System.out.print("Enter the amount: ");
        balance = input.nextDouble();
        input.nextLine();
        String fileName = dir + Integer.toString(accountNumber) + ".txt";
        File f = new File(fileName);
        BufferedReader in = new BufferedReader(new FileReader(fileName));
        Account a = readData(in);
        if (a.balance>balance && balance >0){
            a.balance = a.balance - balance;
            in.close();
            try {
                PrintWriter out = new PrintWriter(new FileWriter(fileName));
                writeData(a, out);
                out.close();
                } catch (IOException e) {
                System.out.print("Error: " + e);
                }
        }
        else System.out.println("Incorrect amount");
        
        System.out.println("Please enter to continue!");
        input.nextLine();//giai phong ky tu enter
        System.out.println("=======================================");
         if(!check)
            functionCustomer(accountNumber);
        else
            functionAdmin(accountNumber);
        
    }
    
    public static void transferMoney(int accountNumber, boolean check) throws ParseException, FileNotFoundException, IOException{
        double amount;
        int dst;
        System.out.println("            |TRANSFER MONEY|");
        System.out.println("---------------------------------------");
        System.out.print("Enter account number: ");
        dst = input.nextInt();
        input.nextLine();
        String fileNamedst = dir + Integer.toString(dst) + ".txt";
        String fileNamesrc = dir+Integer.toString(accountNumber) + ".txt";
        if (accountNumber!=dst){
            try {
            BufferedReader in = new BufferedReader(new FileReader(fileNamedst));
            Account dstAcc = readData(in);
            System.out.println("----------------------------------------");
            System.out.println("Account Name : " + dstAcc.accountName);
            String gender = new String();
            if (dstAcc.gender) gender = "Male"; else gender = "Female";
            System.out.println("Gender       : "+ gender);
            System.out.println("Date of Birth: "+convertDateToString(dstAcc.dateOfBirth));
            System.out.println("----------------------------------------");
            System.out.print("Enter the amount    : ");
            amount = input.nextDouble();
            input.nextLine();
            BufferedReader in0 = new BufferedReader(new FileReader(fileNamesrc));
            Account srcAcc = readData(in0);
            if (srcAcc.balance>amount && amount>0) {
                srcAcc.balance = srcAcc.balance - amount;
                dstAcc.balance = dstAcc.balance + amount;
                System.out.println("Transfer succeed!");
                try {
                PrintWriter out = new PrintWriter(new FileWriter(fileNamedst));
                writeData(dstAcc, out);
                out.close();
                } catch (IOException e) {
                System.out.print("Error: " + e);
                }
                try {
                PrintWriter out1 = new PrintWriter(new FileWriter(fileNamesrc));
                writeData(srcAcc, out1);
                out1.close();
                } catch (IOException e) {
                System.out.print("Error: " + e);
                }
            }
            else System.out.println("Incorrect amount!");
            in.close();
            } catch (IOException e) {
            System.out.println("Invalid account number!");
            }
            }
        else System.out.println("You cannot transfer to yourself!");
            System.out.println("Please enter to continue!");
            input.nextLine();//giai phong ky tu enter
            System.out.println("=======================================");
            if(!check)
                functionCustomer(accountNumber);
            else
                functionAdmin(accountNumber);
        
        
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException {
        // TODO code application logic here
        int accountNumber;
        String password;
        System.out.println("                |LOGIN|");
        System.out.println("=======================================");
        System.out.print("Enter Account Number: ");
        String temp = input.nextLine();
        accountNumber = Integer.parseInt(temp);
        System.out.println("---------------------------------------");
        System.out.print("Enter Password      : ");
        password=input.nextLine();
        System.out.println("---------------------------------------");
        System.out.println("=======================================");
        //creatAccount();
        checkAccount(accountNumber, password);
        //testReadAccount();
        
    }
}
